package com.supor.aiot.common.app;

import android.app.Application;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.mobile.common.lbs.LBSLocation;
import com.alipay.mobile.common.lbs.LBSLocationListener;
import com.alipay.mobile.common.lbs.LBSLocationManagerProxy;
import com.alipay.mobile.framework.quinoxless.QuinoxlessFramework;
import com.alipay.mobile.nebula.provider.H5AppCenterPresetProvider;
import com.alipay.mobile.nebula.util.H5Utils;
import com.alipay.mobile.nebulaappproxy.api.TinyAppRequestPluginProvider;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.mpaas.mas.adapter.api.MPLogger;
import com.mpaas.mps.adapter.api.MPPush;
import com.mpaas.nebula.adapter.api.MPNebula;
import com.mpaas.nebula.adapter.api.MPTinyHelper;
import com.mpaas.tinyappcommonres.TinyAppCenterPresetProvider;
import com.supor.aiot.common.R;
import com.supor.aiot.common.entity.LocationInfo;
import com.supor.aiot.common.entity.UserInfo;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.MediaManager;
import com.supor.aiot.common.helper.WifiStationManager;
import com.supor.aiot.common.helper.WsHelper;
import com.supor.aiot.common.push.NotificationActivity;
import com.supor.aiot.common.ui.view.TinyAppRequestPluginProviderImp;
import com.supor.aiot.common.ui.view.TinyStartupLoadingView;

import java.util.concurrent.TimeUnit;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2021, by het, ShenZhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: AppInit <br>
 * 作者: lei <br>
 * 日期: 2021/11/15 <br>
 */
public class AppInit {
    private static final AppInit ourInstance = new AppInit();
    public static boolean isAppInited;

    public static AppInit getInstance() {
        return ourInstance;
    }

    private AppInit() {
    }

    public void setup(Application app, InitResult result) {
        QuinoxlessFramework.setup(app, () -> {
            Logc.i("QuinoxlessFramework init ok: " + Thread.currentThread().getId());

            ThreadUtils.execute(() -> {
                getUserInfo();
                doRequestLocation();
                // 初始化小程序公共资源包
                // 预置小程序离线包
                H5Utils.setProvider(H5AppCenterPresetProvider.class.getName(),
                        new TinyAppCenterPresetProvider());
                // 设置小程序离线包验签公钥，如需关闭验签，可在 custom_config.json 中，将 h5_shouldverifyapp 的 value 设置成 NO
                MPNebula.enableAppVerification(Constants.App.MPAAS_PUBLIC_KEY);

                SuporPresenter.getInstance().init(AppAgent.getApp());
                MPTinyHelper tinyHelper = MPTinyHelper.getInstance();
                // supor dev
                tinyHelper.setTinyAppVHost(Constants.App.MPAAS_TINY_APP_HOST);

                initPush();
                MPPush.setBadgeAutoClearEnabled(AppAgent.getApp(), true);
                MPPush.setBadgeActivityClassName(AppAgent.getApp(), NotificationActivity.class.getName());

                MPTinyHelper.getInstance().setLoadingViewClass(TinyStartupLoadingView.class);
                MPTinyHelper.getInstance().setAppName(AppAgent.getApp().getResources().getString(R.string.app_name));
                MPTinyHelper.getInstance().setVersionName(SystemUtils.getVerName(AppAgent.getApp()));
                // H5PresetDefaultConfig.mSwitchMap.put("h5_ucCommonSetupConfig", "{\"
                // OPTION_VIDEO_HARDWARE_ACCELERATED\":\"true\"}");

                // 加载mPaaS小程序离线包
                // if (tinyAppId == 0) {
                //     ThreadUtils.execute(() -> MPNebula.loadOfflineNebula("h5_json.json",
                //             new MPNebulaOfflineInfo("1000240220201225_1.0.122.0.amr",
                //                     "1000240220201225", "1.0.122.0")));
                // } else if (tinyAppId == 1) {
                //     ThreadUtils.execute(() -> MPNebula.loadOfflineNebula("h5_json.json",
                //             new MPNebulaOfflineInfo("1000240220201021_1.0.506.0.amr",
                //                     "1000240220201021", "1.0.506.0")));
                // } else {
                //     ThreadUtils.execute(() -> MPNebula.loadOfflineNebula("h5_json.json",
                //             new MPNebulaOfflineInfo("1000240220210519_1.0.67.0.amr",
                //                     "1000240220210519", "1.0.67.0")));
                // }
                Logc.i("attachBaseContext: init " + QuinoxlessFramework.initSuccess());

                if (AppAgent.isPublish) {
                    H5Utils.setProvider(TinyAppRequestPluginProvider.class.getName(),
                            new TinyAppRequestPluginProviderImp("http", 8080));
                } else {
                    H5Utils.setProvider(TinyAppRequestPluginProvider.class.getName(),
                            new TinyAppRequestPluginProviderImp());
                }

            });

        });
    }

    public void onCreate() {
        ThreadUtils.execute(QuinoxlessFramework::init);

        WifiStationManager.initInstance(SuporApplication.getInstance());
        ThreadUtils.execute(() -> {
            MediaManager.getInstance().init();
            getOutNetIp();
        });

        ARouter.init(AppAgent.getApp()); // 尽可能早，推荐在Application中初始化
        isAppInited = true;
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        ThreadUtils.execute(() -> {
            GlobalDataCache.getUniqueId();
            String userInfoStr = BaseSharedPreferences.getString(SuporApplication.getInstance(),
                    Constants.Key.USER_INFO);
            if (TextUtils.isEmpty(userInfoStr)) {
                AppAgent.setLogin(false);
                MPLogger.setUserId("userid_android");
                GlobalDataCache.getAllProduct();
                return;
            }
            // Logc.d("getUserInfo: " + userInfoStr);
            GlobalDataCache.userInfo = GsonUtil.getInstance().toObject(userInfoStr, UserInfo.class);
            AppAgent.setLogin(true);
            WsHelper.getInstance().init(AppAgent.getApp());
            GlobalDataCache.getBindDevice(true);
            GlobalDataCache.getAllProduct();
            SuporPresenter.pushAppToken();
            // Logc.d("getUserInfo: " + userInfo);
            Logc.d("getUserInfo: id: " + GlobalDataCache.userInfo.getBossUserId());

            // 设置mPaaS用户ID，必须设置
            // 1.用户未登录：Android默认设置为userid_android，iOS默认设置为userid_ios；
            // 2.用户已登录：Android和iOS都设置为真实的用户ID。
            MPLogger.setUserId(GlobalDataCache.userInfo.getBossUserId());
        });
    }

    private void getOutNetIp() {
        WifiStationManager.initInstance(SuporApplication.getInstance());
        GlobalDataCache.OUT_IP = WifiStationManager.getOutNetIp();
        Logc.i("getInetAddress: " + GlobalDataCache.OUT_IP);
    }

    /**
     * 初始化push
     */
    private void initPush() {
        ThreadUtils.execute(() -> {
            GlobalDataCache.getUniqueId();
            try {
                MPPush.setup(AppAgent.getApp());
                MPPush.init(AppAgent.getApp());
            } catch (Throwable throwable) {
                Logc.e("initPush: " + throwable.getMessage());
            }
        }, 1800);

    }


    private static final long DEFAULT_LOCATION_INTERVAL = TimeUnit.SECONDS.toMillis(3L);
    private static final long LOCATION_TIME_OUT = TimeUnit.SECONDS.toMillis(4L);

    long locationTime = 0;

    /**
     * 获取定位信息
     */
    public void doRequestLocation() {
        Logc.d("doRequestLocation: " + (locationTime = System.currentTimeMillis()));
        LBSLocationManagerProxy.getInstance().doRequestLocationUpdates(
                // context上下文
                SuporApplication.getInstance(),
                // 是否需要gps
                false,
                // 定位回调
                new LBSLocationListener() {
                    @Override
                    public void onLocationUpdate(LBSLocation lbsLocation) {
                        Logc.d("onLocationUpdate Time: " + (System.currentTimeMillis() - locationTime));
                        getLocationString(lbsLocation);
                        // Logc.d("onLocationUpdate: " + getLocationString(lbsLocation));
                        // SuporPresenter.getInstance().downloadLaunchPage();
                    }

                    @Override
                    public void onLocationFailed(int i) {
                        Logc.d("onLocationUpdate Time: " + (System.currentTimeMillis() - locationTime));
                        // 12 缺少定位权限
                        Logc.d("onLocationFailed: " + i);
                        // SuporPresenter.getInstance().downloadLaunchPage();
                    }
                },
                // 定位时间间隔
                DEFAULT_LOCATION_INTERVAL,
                // 定位超时时间
                LOCATION_TIME_OUT,
                // 是否需要逆地理
                true,
                // biz标识
                Constants.App.TINY_GENERAL,
                // 是否需要速度
                true,
                // 是否是H5
                "F");
    }

    /**
     * 格式化定位信息
     *
     * @param location 定位信息
     * @return
     */
    private String getLocationString(LBSLocation location) {
        LocationInfo locationInfo = new LocationInfo();
        locationInfo.setLongitude(String.valueOf(location.getLongitude()));
        locationInfo.setLatitude(String.valueOf(location.getLatitude()));
        locationInfo.setAdCode(location.getAdCode());
        locationInfo.setCountry(location.getCountry());
        locationInfo.setProvince(location.getProvince());
        locationInfo.setCity(location.getCity());
        locationInfo.setDistrict(location.getDistrict());
        locationInfo.setStreet(location.getStreet());
        locationInfo.setAddress(location.getAddress());
        GlobalDataCache.locationInfo = locationInfo;
        BaseSharedPreferences.setString(AppAgent.getApp(), Constants.Key.LOCATION_INFO,
                GsonUtil.getInstance().toJson(locationInfo));
        Logc.d("onLocationUpdate: " + GsonUtil.getInstance().toJson(locationInfo));
        RxBus3.getInstance().post(Constants.Tag.LOCATION, Constants.Value.SUCCESS);
        return "";

        // StringBuilder sb = new StringBuilder();
        // // 获取经度
        // sb.append("\n经度 longitude : ");
        // sb.append(location.getLongitude());
        // sb.append("\n");
        // // 获取纬度
        // sb.append("纬度 latitude : ");
        // sb.append(location.getLatitude());
        // sb.append("\n");
        // // 获取城市编码
        // sb.append("城市编码 adCode : ");
        // sb.append(location.getAdCode());
        // sb.append("\n");
        // // 获取国家
        // sb.append("国家 country : ");
        // sb.append(location.getCountry());
        // sb.append("\n");
        // // 获取省
        // sb.append("省 province : ");
        // sb.append(location.getProvince());
        // sb.append("\n");
        // // 获取市
        // sb.append("市 city : ");
        // sb.append(location.getCity());
        // sb.append("\n");
        // // 获取区
        // sb.append("区 district : ");
        // sb.append(location.getDistrict());
        // sb.append("\n");
        // // 获取街道
        // sb.append("街道 street : ");
        // sb.append(location.getStreet());
        // sb.append("\n");
        // // 获取地址
        // sb.append("地址 address : ");
        // sb.append(location.getAddress());
        // return sb.toString();
    }

    public interface InitResult {
        void onSuccess();
    }
}
